﻿using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using Matrix.Common.Utility;
using Matrix.Common.Utility.EnumToos;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Enum;
using NPOI.HSSF.UserModel;

namespace Matrix.MaKaYunShang.McMagWeb.Controllers
{
    [Authorization]
    public class UserCardController : BaseController
    {
        #region 分店用户卡券列表

        [PermissionFilter]
        public ActionResult List()
        {
            return View();
        }

        [HttpPost]
        public JsonResult Listing(int draw, int start, int length, string startTime, string endTime, string keyWord, int cateId = 0, int status = -1)
        {
            int order;
            int.TryParse(Request["order[0][column]"], out order);
            var direction = Request["order[0][dir]"];
            var orderByColumns = new[] { "CloudCardId", "CloudCardId", "CardCode", "CardStatus", "AddTime", "VerifyTime", "VerifyMerchantUserId", "ReceiveUserId" };
            var pageIndex = (start / length) + 1;
            var theList = UserCardBLL.Instance.GetPagingList(draw, pageIndex, length, keyWord, orderByColumns[order] + " " + direction, status, CurrentUser.ShopId.ToString(), false, startTime, endTime, cateId);
            return Json(theList);
        }

        #endregion

        #region 总部用户卡券列表

        [PermissionFilter]
        public ActionResult BranchList()
        {
            if (!CurrentUser.IsHeadquarters)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            return View();
        }

        [HttpPost]
        public JsonResult BranchListing(int draw, int start, int length, string startTime, string endTime, string keyWord, string shopName, int cateId = 0, int status = -1)
        {
            if (!CurrentUser.IsHeadquarters)
            {
                return Json(null);
            }
            int order;
            int.TryParse(Request["order[0][column]"], out order);
            var direction = Request["order[0][dir]"];
            var orderByColumns = new[] { "CloudCardId", "CloudCardId", "CardCode", "CardStatus", "AddTime", "VerifyTime", "VerifyMerchantUserId", "ReceiveUserId", "ShopId", "VerifyShopId" };
            var pageIndex = (start / length) + 1;
            string shopIds;
            var subShopList = ShopsBLL.Instance.GetModelList("ParentShopId=" + CurrentUser.ShopId + " or Id=" + CurrentUser.ShopId);
            if (!string.IsNullOrEmpty(shopName))
            {
                var shopList = ShopsBLL.Instance.GetListByName(shopName, inIds: string.Join(",", subShopList.Select(l => l.Id)));
                shopIds = shopList.Count > 0 ? string.Join(",", shopList.Select(l => l.Id)) : "-1";
            }
            else
            {
                shopIds = string.Join(",", subShopList.Select(l => l.Id));
            }
            var theList = UserCardBLL.Instance.GetPagingList(draw, pageIndex, length, keyWord, orderByColumns[order] + " " + direction, status, shopIds, false, startTime, endTime, cateId);
            return Json(theList);
        }

        #endregion

        /// <summary>
        /// 导出用户卡券
        /// </summary>
        [HttpPost]
        public JsonResult ExportUserCards(string keyWord, string startTime, string endTime, int cateId = 0, int status = -1, string shopName = null)
        {
            var result = new Result();
            try
            {
                var shopIds = CurrentUser.ShopId.ToString();
                if (CurrentUser.IsHeadquarters)
                {
                    var subShopList = ShopsBLL.Instance.GetModelList("ParentShopId=" + CurrentUser.ShopId + " or Id=" + CurrentUser.ShopId);
                    if (!string.IsNullOrEmpty(shopName))
                    {
                        var shopList = ShopsBLL.Instance.GetListByName(shopName, inIds: string.Join(",", subShopList.Select(l => l.Id)));
                        shopIds = shopList.Count > 0 ? string.Join(",", shopList.Select(l => l.Id)) : "-1";
                    }
                    else
                    {
                        shopIds = string.Join(",", subShopList.Select(l => l.Id));
                    }
                }
                var userCardList = UserCardBLL.Instance.GetPagingList(0, 1, int.MaxValue, keyWord, "Id asc", status, shopIds, false, startTime, endTime, cateId);

                #region 生成excel文件

                var book = new HSSFWorkbook();
                var sheet = book.CreateSheet("用户卡券数据");
                var titleRow = sheet.CreateRow(0);

                #region 表头
                titleRow.CreateCell(0).SetCellValue("店铺名称");
                titleRow.CreateCell(1).SetCellValue("卡券状态");
                titleRow.CreateCell(2).SetCellValue("卡券类型");
                titleRow.CreateCell(3).SetCellValue("领取时间");
                titleRow.CreateCell(4).SetCellValue("核销人");
                #endregion

                var rowIndex = 1;
                for (var i = 0; i < userCardList.data.Count; i++)
                {
                    var dataRow = sheet.CreateRow(rowIndex);
                    dataRow.CreateCell(0).SetCellValue(userCardList.data[i].ShopName); //店铺名称
                    dataRow.CreateCell(1).SetCellValue(userCardList.data[i].CardStatusText); //卡券状态
                    dataRow.CreateCell(2).SetCellValue(userCardList.data[i].CardCategoryName); //卡券类型
                    dataRow.CreateCell(3).SetCellValue(userCardList.data[i].AddTime.ToString()); //领取时间
                    dataRow.CreateCell(4).SetCellValue(userCardList.data[i].VerifyUserName); //核销人
                    rowIndex++;
                }
                var dataRowLast = sheet.CreateRow(rowIndex);
                dataRowLast.CreateCell(0).SetCellValue("合计（单位时间内）");
                dataRowLast.CreateCell(1).SetCellValue("未使用数量：" + userCardList.data.Count(l => l.CardStatus == (int)CloudCardEnum.UserCardStatus.未使用));
                dataRowLast.CreateCell(2).SetCellValue("已核销数量：" + userCardList.data.Count(l => l.CardStatus == (int)CloudCardEnum.UserCardStatus.已核销));

                var filename = DateTime.Now.ToString("yyyyMMddHHmmss") + CommonHelper.GetGuidKey(6) + ".xls";
                var path = System.Web.HttpContext.Current.Server.MapPath("/Files/UserCard/" + filename);
                if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath("/Files/UserCard/")))
                {
                    Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("/Files/UserCard/"));
                }
                using (var fs = System.IO.File.Create(path))
                {
                    book.Write(fs);
                }
                #endregion

                result.Status = true;
                result.Message = "/Files/UserCard/" + filename;
            }
            catch (Exception ex)
            {
                Logger.Error("UserCardController -- ExportUserCards" + ex);
                result.Message = "系统未知错误，请联系管理员";
            }
            return Json(result);
        }
    }
}